package com.xtkj.accountjava.controller;

import cn.hutool.json.JSONUtil;
import com.xtkj.accountjava.base.BaseException;
import com.xtkj.accountjava.base.Result;
import com.xtkj.accountjava.base.UnauthorizedException;
import com.xtkj.accountjava.entity.AccountBookEntity;
import com.xtkj.accountjava.entity.UserAccountBookEntity;
import com.xtkj.accountjava.entity.UserEntity;
import com.xtkj.accountjava.service.AccountBookService;
import com.xtkj.accountjava.service.LogService;
import com.xtkj.accountjava.service.UserAccountBookService;
import com.xtkj.accountjava.service.UserService;
import com.xtkj.accountjava.utils.RSAUtils;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.expression.AccessException;
import org.springframework.http.HttpHeaders;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/account")
public class AccountBookController {

    @Autowired
    AccountBookService accountBookService;

    @Autowired
    UserAccountBookService userAccountBookService;

    @Autowired
    LogService logService;

    @Autowired
    UserService userService;


    @GetMapping("/account_book_categorys")
    public Result getAccountBookAndCategorysById(
            @RequestHeader(value = HttpHeaders.AUTHORIZATION, required = false) String token,
            @RequestParam Map<String,Object> requestMap
    ){
        UserEntity userEntity = userService.checkToken(token);
        if(userEntity==null){
            throw  new UnauthorizedException("登录过期");
//            throw  new IllegalAccessException("登录过期");
        }
        String requestEntityData = (String) requestMap.get("data");
        HashMap<String,Object> parmsMap = RSAUtils.decryptStrToEntityData(requestEntityData, HashMap.class);
        int saveUserAccountId = Integer.parseInt((String) parmsMap.get("saveUserAccountId")) ;
        UserAccountBookEntity userAccountBooksEntity = userAccountBookService.findUserAccountBooksCategorysById(saveUserAccountId);

        return Result.ok(userAccountBooksEntity) ;
    }
    @GetMapping("/getOnlyAccountBooks/{ids}")
    public Result onlyAccountBooksByIds(@PathVariable(name = "ids") List ids){

        return Result.ok(getOnlyAccountBooksByIds(ids)) ;
    }

    public List<AccountBookEntity> getOnlyAccountBooksByIds(List ids){
        return  accountBookService.findOnlyAccountBooksByIds(ids);
    }

    @GetMapping("/account_book_list")
    public Result getAllAccountBooksAndCategorys(
            @RequestHeader(value = HttpHeaders.AUTHORIZATION, required = false) String token
    ){
        UserEntity userEntity = userService.checkToken(token);
        if(userEntity==null){
            throw  new UnauthorizedException("登录过期");
        }
        return Result.ok(accountBookService.findAllAccountBooksAndCategorys()) ;
    }
    @SneakyThrows
    @GetMapping("/account_book_page")
    public Result getAllAccountBooksAndCategorysByPage(
            @RequestHeader(value = HttpHeaders.AUTHORIZATION, required = false) String token,
            @RequestParam Map<String,Object> requestMap){
        UserEntity userEntity = userService.checkToken(token);
        if(userEntity==null){
            throw  new UnauthorizedException("登录过期");
//            throw  new IllegalAccessException("登录过期");
        }
        String requestEntityData = (String) requestMap.get("data");
        HashMap<String,Object> parmsMap = RSAUtils.decryptStrToEntityData(requestEntityData, HashMap.class);
        int currPage = (int) parmsMap.get("currPage");
        int pageSize = (int) parmsMap.get("pageSize");
        return Result.ok(accountBookService.findAllAccountBooksAndCategorysByPage(currPage,pageSize)) ;
    }
    @GetMapping("/get_accbooks_by_user")
    public Result getAllAccountBooksAndCategorysByUserId(
            @RequestHeader(value = HttpHeaders.AUTHORIZATION, required = false) String token,
            @RequestParam Map<String,Object> requestMap
    ){
        //新建账本列表
        UserEntity userEntity = userService.checkToken(token);
        if(userEntity==null){
            throw  new UnauthorizedException("登录过期");
        }
        String requestEntityData = (String) requestMap.get("data");
        HashMap<String,Object> parmsMap = RSAUtils.decryptStrToEntityData(requestEntityData, HashMap.class);
        int userId = Integer.parseInt((String) parmsMap.get("userId"));
        List<UserAccountBookEntity> allAccountBooksByUserIdEntities = accountBookService.findAllAccountBooksByUserId(userId);
        if(allAccountBooksByUserIdEntities==null)allAccountBooksByUserIdEntities=new ArrayList<>();
        if(allAccountBooksByUserIdEntities.isEmpty()){
            AccountBookEntity onlyAccountBooksByIdEntity = accountBookService.findOnlyAccountBooksById(1);
            
            //如果是第一次，默认插入第一条数据
            UserAccountBookEntity userAccountBookEntity =new UserAccountBookEntity();
            userAccountBookEntity.setUserId(Long.parseLong(userId+""));
            userAccountBookEntity.setAccountBookId(onlyAccountBooksByIdEntity.getId());
            userAccountBookEntity.setAccountBookEntity(onlyAccountBooksByIdEntity);
            userAccountBookEntity.setCreateTime(new Date());
            UserAccountBookEntity userAccountBook = accountBookService.addUserAccountBook(userAccountBookEntity);
            //设置默认账本id到个人信息
            HashMap<String, Object> objectHashMap = new HashMap<>();
            objectHashMap.put("userId",userAccountBook.getUserId());
            objectHashMap.put("defAcbookId",userAccountBook.getId());
            objectHashMap.put("defAcbookName",onlyAccountBooksByIdEntity.getName());
            UserEntity innerEditUser = userService.innerEditUser(objectHashMap);

            //根据账本id，获取账本
            
            userAccountBook.setAccountBookEntity(onlyAccountBooksByIdEntity);
            allAccountBooksByUserIdEntities.add(userAccountBook);

        }
        //accountBookTempEntities 进行遍历查询
//        List<Long> idLists = allAccountBooksByUserId.stream().map(item -> item.getAccountBookId()).collect(Collectors.toList());
        //获取账本集合
//        List<AccountBookEntity> accountBooksByIds = getOnlyAccountBooksByIds(idLists);
        return Result.ok(allAccountBooksByUserIdEntities) ;
    }




    @PostMapping("/add/account_book")
    public Result add_account_book(
            @RequestHeader(value = HttpHeaders.AUTHORIZATION, required = false) String token,
            @RequestParam Map<String,Object> requestMap
    ){
        UserEntity userEntity = userService.checkToken(token);
        if(userEntity==null){
            throw  new UnauthorizedException("登录过期");
        }
        String requestEntityData = (String) requestMap.get("data");
        HashMap<String,Object> parmsMap = RSAUtils.decryptStrToEntityData(requestEntityData, HashMap.class);
        //id	user_id	account_book_id	create_time	description
        int accountBookId = (int) parmsMap.get("accountBookId");
        String description = (String) parmsMap.get("description");

        UserAccountBookEntity userAccountBookEntity =new UserAccountBookEntity();
        userAccountBookEntity.setUserId(Long.parseLong(userEntity.getId()+""));
        userAccountBookEntity.setAccountBookId((long) accountBookId);
        userAccountBookEntity.setCreateTime(new Date());
        userAccountBookEntity.setDescription(description);
        UserAccountBookEntity userAccountBook = accountBookService.addUserAccountBook(userAccountBookEntity);
        if(userAccountBook==null)return  Result.error("添加失败");
        return  Result.ok(userAccountBook);
    }

    @PostMapping("/modify/account_book")
    public Result modify_account_book(
            @RequestHeader(value = HttpHeaders.AUTHORIZATION, required = false) String token,
            @RequestParam Map<String,Object> requestMap
    ){
        UserEntity userEntity = userService.checkToken(token);
        if(userEntity==null){
            throw  new UnauthorizedException("登录过期");
        }
        String requestEntityData = (String) requestMap.get("data");
        HashMap<String,Object> parmsMap = RSAUtils.decryptStrToEntityData(requestEntityData, HashMap.class);
        //id	user_id	account_book_id	create_time	description
        int id = (int) parmsMap.get("id");
        //先查询是否有该账本
        UserAccountBookEntity userAccountBookCheckEntity = userAccountBookService.findOnlyUserAccountBooksById(id);
        if(userAccountBookCheckEntity==null){
            throw  new IllegalArgumentException("修改失败");
        }
        UserAccountBookEntity userAccountBookEntity = JSONUtil.toBean(JSONUtil.toJsonStr(parmsMap), UserAccountBookEntity.class);
        UserAccountBookEntity userAccountBook = accountBookService.updateUserAccountBook(userAccountBookEntity);
        if(userAccountBook==null)return  Result.error("添加失败");
        return  Result.ok(userAccountBook);
    }
}
